import { Upload, Modal } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import React from 'react';
import defaultSetting from '@/../config/defaultSettings';
import { queryImageList } from '../../service';
const { commonUrl, baseUrl } = defaultSetting;
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}

class PicturesWall extends React.Component {
  state = {
    previewVisible: false,
    previewImage: '',
    previewTitle: '',
    fileList: [],
    subpath: '',
  };
  componentDidMount() {
    const { housePictures, CommodityId, subpath } = this.props;

    queryImageList(CommodityId).then((res) => {
      if (res.code === 0){
        this.setState({
          fileList: res.data.map(img=>{
            return {
              id:img.id,
              url:img.url,
              uid:img.id
            }
          }),
          subpath: subpath,
        });
      }
      this.props.handleSetFacePicture(this.state.fileList);
    });
  }

  handleCancel = () => this.setState({ previewVisible: false });

  handlePreview = async (file) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }

    this.setState({
      previewImage: file.url || file.preview,
      previewVisible: true,
      previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
    });
  };
  handleDelete = (val) => {};
  handleChange = ({ fileList }) => {
    this.setState({ fileList });
    let imgArray = [];
    fileList.map((item) => {

      if (item.status === 'done') {
        const {
          response: { data },
        } = item;
        imgArray.push(data);
      }else if(item.id){
        imgArray.push(item);
      }
    });

    this.props.handleSetFacePicture(imgArray);
  };

  render() {
    const { previewVisible, previewImage, fileList, previewTitle, subpath } = this.state;
    const uploadButton = (
      <div>
        <PlusOutlined />
        <div style={{ marginTop: 8 }}>点击上传</div>
      </div>
    );
    return (
      <>
        <Upload
          name="file"
          action={() => {
            return `${baseUrl}common/upload`;
          }}
          listType="picture-card"
          fileList={fileList}
          onPreview={this.handlePreview}
          onChange={this.handleChange}
          onRemove={this.handleDelete}
          data={{ module: subpath }}
          headers={{ token: sessionStorage.getItem('token'), type: 'ADMIN' }}
        >
          {fileList.length >= 8 ? null : uploadButton}
        </Upload>
      </>
    );
  }
}

export default PicturesWall;
